const errorCode = require('errorCode.js')
var Promise = require('es6-promise.js')
var util = require('util.js');

var app = getApp();

function BU01BleUtil(bleParams){
  var deviceId
  var serviceId
  var notifyCharacteristicId
  var writeCharacteristicId
  var available
  var discovering
  
  
  /**
   * 以下为微信蓝牙
   */

  var openBluetoothAdapter = () => new Promise((resolve, reject) =>{
    wx.openBluetoothAdapter({
      success: resolve,
      fail: reject,
    })
  })

  var closeBluetoothAdapter = () => new Promise((resolve, reject) =>{
    wx.closeBluetoothAdapter({
      success: resolve,
      fail: reject,
    })
  })

  var startBluetoothDevicesDiscovery = () => new Promise((resolve,reject)=>{
    wx.startBluetoothDevicesDiscovery({
      services:['FFF0'],
      success: resolve,
      fail: reject,
    })
  })

  var stopBluetoothDevicesDiscovery = () => new Promise((resolve,reject) => {
    wx.stopBluetoothDevicesDiscovery({
      success: resolve,
      fail: reject,
    })
  })

  var createBLEConnection = (id) => new Promise((resolve, reject) => {
    wx.createBLEConnection({
      deviceId: id,
      success: resolve,
      fail: reject,
    })
  })

  var getBLEDeviceServices = (connectedDeviceId) => new Promise((resolve, reject) =>{
    wx.getBLEDeviceServices({
      deviceId: connectedDeviceId,
      success: resolve,
      fail: reject,
    })
  })

  var getBLEDeviceCharacteristics = (connectedDeviceId, serviceId) => new Promise((resolve, reject) => {
    wx.getBLEDeviceCharacteristics({
      deviceId: connectedDeviceId,
      serviceId: serviceId,
      success: resolve,
      fail: reject,
    })
  })

  var notifyBLECharacteristicValueChange = (connectedDeviceId, serviceId, characteristicId) => new Promise((resolve,reject) => {
    wx.notifyBLECharacteristicValueChange({
      deviceId: connectedDeviceId,
      serviceId: serviceId,
      characteristicId: characteristicId,
      state: true,
      success: resolve,
      fail: reject,
    })
  })

  var closeBLEConnection = (connectedDeviceId) => new Promise((resolve, reject) => {
    wx.closeBLEConnection({
      deviceId: connectedDeviceId,
      success: resolve,
      fail: reject,
    })
  })

  /**
   * 以下为对外蓝牙接口
   */

  /**
   * 初始化蓝牙
   */
  this.iniBle = () => openBluetoothAdapter()
    .then(res => {
      console.log('蓝牙初始化成功', JSON.stringify(res))   
      wx.onBluetoothAdapterStateChange(res =>{
        available = res.available ? true : false;
        discovering: res.discovering ? true : false;
        console.log("蓝牙状态变化", available);
        app.globalData.available = available
        app.globalData.discovering = discovering
      });
      return startBluetoothDevicesDiscovery()
    }).then(() => {
    var then = this
      wx.showLoading({
        title: '搜索蓝牙中...',
        mask: true
      })
      
      app.globalData.available = true
      app.globalData.discovering = true
      //  this.onBluetoothDeviceFound(res=>{
      //   console.log("蓝牙搜索成功", JSON.stringify(res));

      //   res.devices.forEach(device => {
      //     if (!device.name && !device.localName) {
      //       return
      //     }
      //     if (device.name == bleParams.deviceCode) {
      //       deviceId = device.deviceId;
      //     }
      //   })
      //   if (deviceId) {
      //     return stopBluetoothDevicesDiscovery().then(() => {
      //       wx.showLoading({
      //         title: '连接中...',
      //         mask: true
      //       })
      //       return this.connect(deviceId)
      //     });
      //   }
      // })
    })
  /**
   * 关闭蓝牙
   */
  this.closeBle = () => closeBluetoothAdapter()
    .then(res => {
      app.globalData.connection = false;
      console.log('关闭蓝牙成功', JSON.stringify(res))
    })
  /**
   * 开始搜索蓝牙
   */
  this.start = () => startBluetoothDevicesDiscovery()
    .then(res => {
      console.log('开始搜索', JSON.stringify(res))
    })
  /**
   * 停止搜索蓝牙
   */
  this.stop = () => stopBluetoothDevicesDiscovery()
    .then(res =>{
      console.log('停止搜索', JSON.stringify(res))
    })

  /**
   * 蓝牙连接
   */
  this.connect = (deviceId) => createBLEConnection(deviceId)
    .then(res => {
      console.log('连接成功', JSON.stringify(res))
      app.globalData.connectedDeviceId = deviceId
      return getBLEDeviceServices(deviceId)
    })
    .then(res => {
      console.log('获取蓝牙服务成功', JSON.stringify(res))   
      var serviceIds = JSON.stringify(res.services).match(new RegExp(/0001(ABCD|abcd)[0-9a-fA-F\-]+/))
      if (serviceIds == null) {
        return Promise.reject('找不到对应服务10004')
      }
      console.log('serviceId:', serviceIds[0])
      serviceId = serviceIds[0]
      app.globalData.serviceId = serviceId
      return getBLEDeviceCharacteristics(deviceId, serviceId)
    })
    .then(res => {
      console.log('获取特征值成功', JSON.stringify(res.characteristics))
      for (let i = 0; i < res.characteristics.length; i++) {
        let item = res.characteristics[i]
        if (item.properties.notify){
          notifyCharacteristicId = item.uuid;
        }
        if (item.properties.write){
          writeCharacteristicId = item.uuid;
        }
      }
      console.log(notifyCharacteristicId)
      console.log(writeCharacteristicId)
      app.globalData.notifyCharacteristicId = notifyCharacteristicId
      app.globalData.writeCharacteristicId = writeCharacteristicId
      return notifyBLECharacteristicValueChange(deviceId, serviceId, notifyCharacteristicId)
    })
    .then(res => {
      app.globalData.connection = true;
      console.log('启用notify功能成功', JSON.stringify(res.errMsg))   
      this.error = new errorCode.ErrorCode()
      wx.onBLEConnectionStateChange(res => {
        console.log('连接状态变化', JSON.stringify(res))   
        if (!res.connected) {
          app.globalData.connection = false;
          this.error.getErrorMsg('蓝牙连接已断开', '10008')
          this.closeBle()
        }
      })
    })

  /**
   * 断开蓝牙连接
   */
  this.disconnect = (connectedDeviceId) => closeBLEConnection(connectedDeviceId)
    .then(res => {
      console.log('断开连接成功', res)
    })
    .catch(res => {
      console.log('断开连接失败', res)
    })

  /**
   * 发现蓝牙设备回调
   */
  this.onBluetoothDeviceFound = (callback) => {
    wx.onBluetoothDeviceFound(res => {
      callback(res)
    })
  }

  /**
   * 蓝牙状态改变回调
   */
  this.onBluetoothAdapterStateChange = (callback) => {
    wx.onBluetoothAdapterStateChange(res => {
      callback(res)
    })
  }
  this.findDevices = (callback) => {
    wx.showLoading({
      title: '等待设备...',
      mask: true
    })
    console.log('搜索设备', bleParams.deviceCode)
    //也可以直接调用微信接口
    this.onBluetoothDeviceFound(res => {
      console.log('发现新设备', JSON.stringify(res))
      //不同平台的设备使用该回调会有不同的参数，需要逐个处理
      var device;
      if (res.deviceId) {
        device = res
      }
      else if (res.devices) {
        device = res.devices[0];
      }
      else {
        device = res.devices[0][0];
      }

      if (!device.name && !device.localName) {
        return
      }
      if (device.localName == bleParams.deviceCode || device.name == bleParams.deviceCode) {
        deviceId = device.deviceId;
      }
      if (deviceId) {
        return stopBluetoothDevicesDiscovery().then(() => {
          wx.hideToast();
          wx.showLoading({
            title: '连接中...' +bleParams.deviceCode,
            mask: true
          })
          callback(deviceId);
        });
      }
    })
  }
}
module.exports = {
  BU01BleUtil: BU01BleUtil,
}